import { Router } from '@angular/router';
import { Component, OnInit, Input } from '@angular/core';

import { AlertController } from '@ionic/angular';

import { HttpService } from 'src/app/shared/service/http.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { EventService } from './../../shared/service/event.service';
import { ChatService } from 'src/app/shared/service/chatService';

@Component({
  selector: 'app-custom-phone',
  templateUrl: './custom-phone.component.html',
  styleUrls: ['./custom-phone.component.scss'],
})
export class CustomPhoneComponent implements OnInit {
  @Input() tagData: any = {};
  userData: any = undefined;
  constructor(
    public router: Router,
    public alertController: AlertController,
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private chatService: ChatService,

    private eventService: EventService
  ) { }

  ngOnInit() {
    this.eventService.eventEmit.on("userInfo", userInfo => {
      this.tagData.data.userInfo = JSON.parse(userInfo);
    });
  }

  /**
   * user按钮
   */
  async userSubmit(uid, con) {
    console.log(uid, con);
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: '确定要查看号码吗？',
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          const params = {
            content: con,
            id: uid,
            sessionId: localStorage.getItem("sessionId")
          };
          this.http.post("application/submit", params, res => {
            if (res.success) {
              console.log(res);
              this.userData = res.data;
              this.tagData.data.userInfo.phone = this.userData.phone;
            } else {
              this.appGlobalService.showToast(res.message, 1000, "top");
            }
          });
        }
      }]
    });
    await alert.present();
  }

  // 打电话
  async call(e) {
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: e,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('取消');
        }
      }, {
        text: '拨打',
        cssClass: 'LJ',
        handler: () => {
          this.http.changeCallNumber(e);
        }
      }]
    });
    await alert.present();
  }

  // 聊天
  chat(obj, loginPage) {
    const cityId = JSON.parse(localStorage.getItem('position')) ? JSON.parse(localStorage.getItem('position')).code : 4403;
    if (localStorage.getItem('userId')) {
      this.http.getImId(obj.params.opportunity_id,
        obj.params.customer_id, cityId, (item) => {
          if (item.toId !== localStorage.getItem('userId')) {
            const userId = item.toId;
            if (this.chatService.getAvatar(userId)) {
              this.eventService.eventEmit.emit('enterChatRoomByUserId',
                {
                  userId,
                  fromFriendList: true,
                  friendName: this.chatService.nickNames[userId],
                  friendAvatar: this.chatService.getAvatar(userId)
                });
            } else {
              this.http.get(
                "message/userinfo/im/" + userId,
                response => {
                  const data = response.data;
                  if (data) {
                    if (data.avatar_url === null) { // 没头像给默认头像
                      data.avatar_url = this.appGlobalService.defaultImg;
                      this.chatService.setAvatar(userId, this.chatService.defaultBase64String);
                    } else {
                      this.appGlobalService.getBase64Str(data.avatar_url + "?x-oss-process=image/resize,h_36", str => {
                        this.chatService.setAvatar(userId, str);
                      });
                    }
                    this.chatService.nickNames[userId] = data.nickname;
                    this.eventService.eventEmit.emit('enterChatRoomByUserId',
                      {
                        userId,
                        fromFriendList: true,
                        friendName: data.nickname,
                        friendAvatar: data.avatar_url
                      });
                  }
                });
            }
          }
        });
    } else if (loginPage) {
      const pageParams = {
        pageId: loginPage,
        params: { skip: 0 },
        sessionId: localStorage.getItem('sessionId')
      };
      localStorage.setItem('isDetailPage', 'true');
      this.appGlobalService.goToForward(pageParams);
    }
  }
}
